import React from 'react'
import { InputProps } from './types'
import classNames from 'classnames'
import Icon from '../Icon/icon'

const Input: React.FC<InputProps> = (props) => {
	const { disabled, size, icon, prepend, append, style, ...restProps } = props

	const classes = classNames('v-input-wrapper', {
		[`input-size-${size}`]: size,
		'is-disabled': disabled,
		'input-group': prepend || append,
		'input-group-append': !!append,
		'input-group-prepend': !!prepend
	})

	const fixControlledValue = (value: any) => {
		if (typeof value === 'undefined' || value === null) {
			return ''
		}

		return value
	}

	if ('value' in props) {
		delete restProps.defaultValue
		restProps.value = fixControlledValue(props.value)
	}

	return (
		<div className={classes} style={style}>
			{prepend && <div className="v-input-group-prepend">{prepend}</div>}
			{icon && (
				<div className="icon-wrapper">
					<Icon icon={icon} title={`title-${icon}`} />
				</div>
			)}
			<input className="v-input-inner" disabled={disabled} {...restProps} />
			{append && <div className="v-input-group-append">{append}</div>}
		</div>
	)
}

export default Input
